var express = require('express');
const { ISO_8601 } = require('moment');
var router = express.Router();
var moment = require('moment');
var query = require('../config/db');
// 查询用户列表
router.get('/test',(req, res, next) => {
  return res.json({'success':true,'data':11111})
})
// 查询用户列表
router.post('/user',(req, res, next) => {
  var pageSize = req.body.pageSize || 1000;
  var index = ((req.body.currentPage || 1)-1)*pageSize;
  query('SELECT * FROM user LIMIT '+index+' , '+pageSize, (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      return res.json({'success':true,'data':result})
    }
  });
})
//用户登录校验
router.post('/checkUser',function(req, res, next){
  var username = req.body.name;
  var password = req.body.password;
  query("SELECT * FROM user WHERE account= '"+username+"' AND password= '"+password+"'", (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      debugger
      if(result && result.length>0) {
        if(result[0].enable === '1') {
          if(new Date(result[0].startdate).getTime() < new Date().getTime() && new Date().getTime()<new Date(result[0].enddate).getTime()+24*60*60*1000) {
            return res.json({'success':true,'data':{isOk:true,username:result[0].username}})
          }else {
            return res.json({'success':true,'data':{isOk:false,username:null,msg:'该账户已过期，请联系管理员。'}})
          }
        }else {
          return res.json({'success':true,'data':{isOk:false,username:null,msg:'该账户已被冻结，请联系管理员。'}})
        }
      }else {
        return res.json({'success':true,'data':{isOk:false,username:null,msg:'账户名或密码错误'}})
      }
      
    }
  })
});
// 查询项目列表
router.post('/projects',(req, res, next) => {
  var pageSize = req.body.pageSize || 1000;
  var index = ((req.body.currentPage || 1)-1)*pageSize;
  query('SELECT id,title,pubtime,brief,startdate,enddate,technology,image FROM project LIMIT '+index+' , '+pageSize, (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      result.forEach(item => {
        item.startdate = moment(item.startdate).utcOffset(8).format('YYYY-MM-DD')
        item.enddate = moment(item.enddate).utcOffset(8).format('YYYY-MM-DD')
      })
      return res.json({'success':true,'data':result})
    }
  });
})
//根据项目id查询详情
router.post('/queryProjectsById',function(req, res, next){
  var id = req.body.id;
  query('SELECT * FROM project WHERE id='+id, (err, result)=> {    
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      if(result.length>0) {
        result[0].startdate = moment(result[0].startdate).utcOffset(8).format('YYYY-MM-DD')
        result[0].enddate = moment(result[0].enddate).utcOffset(8).format('YYYY-MM-DD')
        return res.json({'success':true,'data':result[0]})
      }else {
        return res.json({'success':true,'data':{}})
      }
    }
  })
});
// 新增项目
router.post('/addProject',(req, res, next) => {
  var title = req.body.title;
  var content = req.body.content;
  var brief = req.body.brief;
  var technology = req.body.technology;
  var startdate = req.body.startdate;
  var enddate = req.body.enddate;
  var image = req.body.image;
  if(title && content && technology) {
    query("INSERT INTO project (title, content, brief, technology, startdate, enddate, image) VALUES ('"+title+"', '"+content+"', '"+brief+"', '"+technology+"', '"+startdate+"', '"+enddate+"', '"+image+"')", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        console.log('result',result);
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
        
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'参数不合法'})
  }
})
// 编辑项目
router.post('/updateProject',(req, res, next) => {
  var id = req.body.id;
  var title = req.body.title;
  var content = req.body.content;
  var brief = req.body.brief;
  var technology = req.body.technology;
  var startdate = req.body.startdate;
  var enddate = req.body.enddate;
  var image = req.body.image;
  if(title && content && technology && id) {
    query("UPDATE project set title='"+title+"', content='"+content+"', brief='"+brief+"',technology='"+technology+"',startdate='"+startdate+"',enddate='"+enddate+"', image='"+image+"' WHERE id="+id, (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
        
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'参数不合法'})
  }
})
// 删除项目
router.post('/deleteProject',(req, res, next) => {
  var id = req.body.id;
  if(id) {
    query("DELETE FROM project WHERE id="+id, (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        console.log(11,result);
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要删除项目的ID'})
  }
})
// 查询文章分类值集
router.post('/tags',(req, res, next) => {
  query('SELECT * FROM tags', (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      return res.json({'success':true,'data':result})
    }
  });
})
// 分页查询文章列表
router.post('/articles',(req, res, next) => {
  var pageSize = req.body.pageSize || 10;
  var index = (req.body.currentPage-1)*pageSize;
  query('SELECT id,title,pubtime,brief,tag_id,hits,bad,good,image FROM article LIMIT '+index+' , '+pageSize, (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      result.forEach(item => {
        item.pubtime = moment(item.pubtime).utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
      })
      return res.json({'success':true,'data':result})
    }
  });
})
//根据文章id查询文章
router.post('/queryArticleById',function(req, res, next){
  var id = req.body.id;
  query('SELECT * FROM article WHERE id='+id, (err, result)=> {    
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      if(result.length>0) {
        return res.json({'success':true,'data':result[0]})
      }else {
        return res.json({'success':true,'data':{}})
      }
    }
  })
});
// 新增文章
router.post('/addArticles',(req, res, next) => {
  var title = req.body.title;
  var content = req.body.content;
  var brief = req.body.brief;
  var tag_id = req.body.tag_id;
  var image = req.body.image;
  if(title && content && tag_id) {
    query("INSERT INTO article (title, content, brief, tag_id, image) VALUES ('"+title+"', '"+content+"', '"+brief+"', '"+tag_id+"', '"+image+"')", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
        
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'参数不合法'})
  }
})
// 编辑文章
router.post('/updateArticles',(req, res, next) => {
  var id = req.body.id;
  var title = req.body.title;
  var content = req.body.content;
  var brief = req.body.brief;
  var tag_id = req.body.tag_id;
  var image = req.body.image;
  if(title && content && tag_id && id) {
    query("UPDATE article set title='"+title+"', content='"+content+"', brief='"+brief+"',tag_id='"+tag_id+"', image='"+image+"' WHERE id="+id, (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
        
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'参数不合法'})
  }
})
// 删除文章
router.post('/deleteArticles',(req, res, next) => {
  var id = req.body.id;
  if(id) {
    query("DELETE FROM article WHERE id="+id, (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        console.log(11,result);
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要删除文章的ID'})
  }
})

// 查询留言表
router.post('/discuss',(req, res, next) => {
  var pageSize = req.body.pageSize || 1000;
  var index = ((req.body.currentPage || 1)-1)*pageSize;
  query('SELECT * FROM discuss LIMIT '+index+' , '+pageSize, (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      return res.json({'success':true,'data':result})
    }
  });
})
// 新增留言表
router.post('/addDiscuss',(req, res, next) => {
  var name = req.body.name;
  var tel = req.body.tel;
  var email = req.body.email;
  var content = req.body.content;
  if(!name || !tel || !email || !content) {
    return res.status(500).send({'success':false,'msg':'参数不合法'})
  }
  query("INSERT INTO discuss (name, tel, email, content) VALUES ('"+name+"', '"+tel+"', '"+email+"', '"+content+"')", (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      if(result.affectedRows>0) {
        return res.json({'success':true,'data':true})
      }else {
        return res.json({'success':true,'data':false})
      }
      
    }
  });
})

// 查询用户列表
router.post('/userList',(req, res, next) => {
  var pageSize = req.body.pageSize || 1000;
  var index = ((req.body.currentPage || 1)-1)*pageSize;
  let total = 0;
  query('SELECT count(*) as num from user', (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      result = JSON.parse(JSON.stringify(result))
      total = result[0].num;
      if(total === 0) {
        return res.json({'success':true,'data':{list:[],len:total}})
      }
      query('SELECT * FROM user LIMIT '+index+' , '+pageSize, (err, result)=> {
        if(err) {
          console.log(err);
          err.success = false;
          return res.status(500).send(err)
        }else {
          result.forEach(item => {
            item.startdate = moment(item.startdate).utcOffset(8).format('YYYY-MM-DD')
            item.enddate = moment(item.enddate).utcOffset(8).format('YYYY-MM-DD')
          })
          return res.json({'success':true,'data':{list:result,len:total}})
        }
      });
    }
  })
})
// 新增或编辑用户列表
router.post('/addOrEditUser',(req, res, next) => {
  var id = req.body.id;
  var username = req.body.username;
  var account = req.body.account;
  var password = req.body.password;
  var enable = req.body.enable;
  var startdate = req.body.startdate;
  var enddate = req.body.enddate;
  // 编辑
  if(id) {
    if(id && username && account && password && enable && startdate && enddate) {
      query("UPDATE user set username='"+username+"', account='"+account+"', password='"+password+"',enable='"+enable+"',startdate='"+startdate+"', enddate='"+enddate+"' WHERE id="+id, (err, result)=> {
        if(err) {
          console.log(err);
          err.success = false;
          return res.status(500).send(err)
        }else {
          if(result.affectedRows>0) {
            return res.json({'success':true,'data':true})
          }else {
            return res.json({'success':true,'data':false})
          }
        }
      });
    }else {
      return res.status(500).send({'success':false,'msg':'参数不合法'})
    }
  // 新增
  }else {
    if(username && account && password && enable && startdate && enddate) {
      query("SELECT account FROM user WHERE account= '"+account+"'", (err,result) => {
        if(result.length > 0) {
          return res.json({'success':true,'data':false})
        }else {
          query("INSERT INTO user (username , account , password , enable , startdate , enddate) VALUES ('"+username+"', '"+account+"', '"+password+"', '"+enable+"', '"+startdate+"', '"+enddate+"')", (err, result)=> {
            if(err) {
              console.log(err);
              err.success = false;
              return res.status(500).send(err)
            }else {
              console.log('result',result);
              if(result.affectedRows>0) {
                return res.json({'success':true,'data':true})
              }else {
                return res.json({'success':true,'data':false})
              }
            }
          });
        }
        console.log(1,result);
      })
      
    }else {
      return res.status(500).send({'success':false,'msg':'参数不合法'})
    }
  }
})
// 启用或冻结用户
router.post('/enableOrDisableUser',(req, res, next) => {
  var ids = req.body.ids;
  var type = req.body.type;
  ids = ids.join(',');
  if(ids) {
    query("UPDATE user SET enable='"+type+"'  WHERE id in ("+ids+")", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要处理的用户'})
  }
})
// 删除用户列表
router.post('/deleteUser',(req, res, next) => {
  var ids = req.body.ids;
  ids = ids.join(',');
  if(ids) {
    query("DELETE FROM user WHERE id in ("+ids+")", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要删除的用户'})
  }
})

// 查询友情链接
router.post('/links',(req, res, next) => {
  var pageSize = req.body.pageSize || 1000;
  var index = ((req.body.currentPage || 1)-1)*pageSize;
  let total = 0;
  query('SELECT count(*) as num from links', (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      result = JSON.parse(JSON.stringify(result))
      total = result[0].num;
      if(total === 0) {
        return res.json({'success':true,'data':{list:[],len:total}})
      }
      query('SELECT * FROM links LIMIT '+index+' , '+pageSize, (err, result)=> {
        if(err) {
          console.log(err);
          err.success = false;
          return res.status(500).send(err)
        }else {
          result.forEach(item => {
            item.pubtime = moment(item.pubtime).utcOffset(8).format('YYYY-MM-DD')
          })
          return res.json({'success':true,'data':{list:result,len:total}})
        }
      });
    }
  })
})
// 新增或编辑链接
router.post('/addOrEditLink',(req, res, next) => {
  var id = req.body.id;
  var title = req.body.title;
  var url = req.body.url;
  var pubtime = req.body.pubtime || moment().format('YYYY-MM-DD HH:mm:ss');
  var brief = req.body.brief;
  var image = req.body.image || "";
  // 编辑
  if(id) {
    if(id && title && url && brief) {
      query("UPDATE links set title='"+title+"', url='"+url+"', pubtime='"+pubtime+"',brief='"+brief+"', image='"+image+"' WHERE id="+id, (err, result)=> {
        if(err) {
          console.log(err);
          err.success = false;
          return res.status(500).send(err)
        }else {
          if(result.affectedRows>0) {
            return res.json({'success':true,'data':true})
          }else {
            return res.json({'success':true,'data':false})
          }
        }
      });
    }else {
      return res.status(500).send({'success':false,'msg':'参数不合法'})
    }
  // 新增
  }else {
    if(title && url && brief) {
      query("INSERT INTO links (title , url , pubtime , brief , image ) VALUES ('"+title+"', '"+url+"', '"+pubtime+"', '"+brief+"', '"+image+"')", (err, result)=> {
        if(err) {
          console.log(err);
          err.success = false;
          return res.status(500).send(err)
        }else {
          console.log('result',result);
          if(result.affectedRows>0) {
            return res.json({'success':true,'data':true})
          }else {
            return res.json({'success':true,'data':false})
          }
        }
      });
    }else {
      return res.status(500).send({'success':false,'msg':'参数不合法'})
    }
  }
})
// 删除友情链接
router.post('/deleteLink',(req, res, next) => {
  var ids = req.body.ids;
  ids = ids.join(',');
  if(ids) {
    query("DELETE FROM links WHERE id in ("+ids+")", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要删除的友情链接'})
  }
})

// 查询留言
router.post('/discussList',(req, res, next) => {
  var pageSize = req.body.pageSize || 1000;
  var index = ((req.body.currentPage || 1)-1)*pageSize;
  let total = 0;
  query('SELECT count(*) as num from discuss', (err, result)=> {
    if(err) {
      console.log(err);
      err.success = false;
      return res.status(500).send(err)
    }else {
      result = JSON.parse(JSON.stringify(result))
      total = result[0].num;
      if(total === 0) {
        return res.json({'success':true,'data':{list:[],len:total}})
      }
      query('SELECT * FROM discuss LIMIT '+index+' , '+pageSize, (err, result)=> {
        if(err) {
          console.log(err);
          err.success = false;
          return res.status(500).send(err)
        }else {
          result.forEach(item => {
            item.pubtime = moment(item.pubtime).utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
          })
          return res.json({'success':true,'data':{list:result,len:total}})
        }
      });
    }
  })
})
// 启用或冻结留言
router.post('/enableOrDisableDiscuss',(req, res, next) => {
  var ids = req.body.ids;
  var type = req.body.type;
  ids = ids.join(',');
  if(ids) {
    query("UPDATE discuss SET enable='"+type+"'  WHERE id in ("+ids+")", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要处理的留言'})
  }
})
// 删除留言
router.post('/deleteDiscuss',(req, res, next) => {
  var ids = req.body.ids;
  ids = ids.join(',');
  if(ids) {
    query("DELETE FROM discuss WHERE id in ("+ids+")", (err, result)=> {
      if(err) {
        console.log(err);
        err.success = false;
        return res.status(500).send(err)
      }else {
        if(result.affectedRows>0) {
          return res.json({'success':true,'data':true})
        }else {
          return res.json({'success':true,'data':false})
        }
      }
	  });
  }else {
	  return res.status(500).send({'success':false,'msg':'请选择要删除的友情链接'})
  }
})
module.exports = router;